<template lang="pug">
.flap-card-wrapper(v-show="flapCardVisible")
  .flap-card-bg(
    :class="{'animation': runFlapCardAnimation}"
    v-show="!runBookCardAnimation"
    )
    .flap-card(v-for="(item, index) in flapCardList"
    :key="index"
    :style="{ zIndex:item.zIndex }"
    )
      .flap-card-circle
        .flap-card-semi-circle.flap-card-semi-circle-left(
          :style="semiCircleStyle(item,'left')"
          ref="left"
        )
        .flap-card-semi-circle.flap-card-semi-circle-right(
          :style="semiCircleStyle(item,'right')"
          ref="right"
        )
    .point-wrapper
      .point(v-for="(item) in pointList"
       :key="item"
       :class="{'animation': runPointAnimation }")
  .book-card(
    :class="{'animation':runBookCardAnimation}"
    v-if="runBookCardAnimation"
    )
    .book-card-wrapper
      .img-wrapper
        img.img(v-lazy="data.cover")
      .content-wrapper
        .content-title {{data ? data.title : ''}}
        .content-author.sub-title-medium {{ data ? data.author : ''}}
        .content-category {{ categoryText() }}
      .read-btn(@click.stop="showBookDetail(data)") {{$t('home.readNow')}}
  .close-btn-wrapper(@click="close")
    span.icon-close
</template>

<script>
import { storeHomeMixin } from '@/utils/mixin'
import { flapCardList, categoryText } from '@/utils/store'

export default {
  name: 'FlapCard',
  mixins: [storeHomeMixin],
  props: {
    data: {
      type: Object
    }
  },
  data() {
    return {
      flapCardList,
      front: 0,
      back: 1,
      intervalTime: 25,
      task: null,
      runFlapCardAnimation: false,
      runPointAnimation: false,
      pointList: null,
      runBookCardAnimation: false
    }
  },
  watch: {
    flapCardVisible(v) {
      if (v) {
        this.runAnimation()
      }
    }
  },
  methods: {
    /**
     * 关闭
     */
    close() {
      this.stopAnimation()
      this.setFlapCardVisible(false)
    },
    /**
     * 设置半圆的样式
     * @param {Object} item
     * @param {String} dir
     * @returns {{backgroundColor: string, backgroundImage: (*), backgroundSize: (string|string)}}
     */
    semiCircleStyle(item, dir) {
      return {
        backgroundColor: `rgb(${item.r}, ${item.g}, ${item.b})`,
        backgroundSize: item.backgroundSize,
        backgroundImage: dir === 'left' ? item.imgLeft : item.imgRight
      }
    },
    /**
     * 转动的核心方法
     * @param {Number} index 第几个圆
     * @param {String} type 是正面还是背面
     */
    rotate(index, type) {
      const item = this.flapCardList[index]
      let dom
      if (type === 'front') {
        dom = this.$refs.right[index]
      } else {
        dom = this.$refs.left[index]
      }
      dom.style.transform = `rotateY(${item.rotateDegree}deg)`
      dom.style.backgroundColor = `rgb(${item.r},${item._g},${item.b})`
    },
    /**
     * 转动卡片的核心方法
     */
    flapCardRotate() {
      const frontFlapCard = this.flapCardList[this.front]
      const backFlapCard = this.flapCardList[this.back]
      frontFlapCard.rotateDegree += 10
      frontFlapCard._g -= 5
      backFlapCard.rotateDegree -= 10
      // 当转动的角度小于90时,才开始变淡颜色
      if (backFlapCard.rotateDegree < 90) {
        backFlapCard._g += 5
      }
      // 第一个临界点: 两个半圆都为90deg
      if (frontFlapCard.rotateDegree === 90 && backFlapCard.rotateDegree === 90) {
        backFlapCard.zIndex += 2
      }
      this.rotate(this.front, 'front')
      this.rotate(this.back, 'back')
      // 第二个临界点: 上半圆转动180deg,下半圆转动为0时,调用下一次的卡片
      if (frontFlapCard.rotateDegree === 180 && backFlapCard.rotateDegree === 0) {
        this.next()
      }
    },
    /*
     *  索引加,并动态设置zindex 使之生效
     * */
    next() {
      const frontFlapCard = this.flapCardList[this.front]
      const backFlapCard = this.flapCardList[this.back]
      frontFlapCard._g = frontFlapCard.g
      frontFlapCard.rotateDegree = 0
      backFlapCard._g = backFlapCard.g
      backFlapCard.rotateDegree = 0
      this.rotate(this.front, 'front')
      this.rotate(this.back, 'back')
      this.front++
      this.back++
      const len = this.flapCardList.length
      if (this.front >= len) {
        this.front = 0
      }
      if (this.back >= len) {
        this.back = 0
      }
      // 动态设置z-index
      this.flapCardList.forEach((item, index) => {
        item.zIndex = 100 - ((index - this.front + len) % len)
      })
      this.prepare()
    },
    /*
     * 使下半圆与上半圆进行重合
     * */
    prepare() {
      const backFlapCard = this.flapCardList[this.back]
      backFlapCard.rotateDegree = 180
      backFlapCard._g = backFlapCard.g - 5 * 9
      this.rotate(this.back, 'back')
    },
    /*
     *  停止动画,以及重置样式
     * */
    stopAnimation() {
      if (this.task) {
        clearInterval(this.task)
      }
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.reset()
    },
    /*
     *  重置样式
     * */
    reset() {
      this.front = 0
      this.back = 1
      this.flapCardList.forEach((item, index) => {
        item.zIndex = 100 - index
        item._g = item.g
        item.rotateDegree = 0
        this.rotate(index, 'front')
        this.rotate(index, 'back')
      })
      this.runBookCardAnimation = false
      this.runFlapCardAnimation = false
      this.runPointAnimation = false
    },
    /*
     *  开始卡片翻转动画
     * */
    startFlapCardAnimation() {
      this.prepare()
      this.task = setInterval(() => {
        this.flapCardRotate()
      }, this.intervalTime)
    },
    runAnimation() {
      this.runFlapCardAnimation = true
      setTimeout(() => {
        this.startFlapCardAnimation()
        this.startPointAnimation()
      }, 300)

      //  模拟请求api
      this.timeout = setTimeout(() => {
        this.stopAnimation()
        this.runBookCardAnimation = true
      }, 2500)
    },
    startPointAnimation() {
      this.runPointAnimation = true
      setTimeout(() => {
        this.runPointAnimation = false
      }, 1500)
    },
    categoryText() {
      if (this.data) {
        return categoryText(this.data.category, this)
      } else {
        return ''
      }
    }
  },
  created() {
    this.pointList = []
    for (let i = 0; i < 18; i++) {
      this.pointList.push(`point${i}`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/styles/global';
@import '~@/assets/styles/flapCard';
.flap-card-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1000;
  background: #0006;
  height: 100%;
  width: 100%;
  @include center;
  .flap-card-bg {
    position: relative;
    width: px2rem(64);
    height: px2rem(64);
    border-radius: px2rem(5);
    background: white;
    transform: scale(0);
    opacity: 0;
    &.animation {
      animation: flap-card-move 0.3s ease-in;
      animation-fill-mode: forwards;
    }
    @keyframes flap-card-move {
      0% {
        transform: scale(0);
        opacity: 0;
      }
      50% {
        transform: scale(1.2);
        opacity: 1;
      }
      75% {
        transform: scale(0.9);
        opacity: 1;
      }
      100% {
        transform: scale(1);
        opacity: 1;
      }
    }
    .flap-card {
      width: px2rem(48);
      height: px2rem(48);
      @include absCenter;
      .flap-card-circle {
        display: flex;
        width: 100%;
        height: 100%;

        .flap-card-semi-circle {
          flex: 0 0 50%;
          width: 50%;
          height: 100%;
          background-repeat: no-repeat;
          backface-visibility: hidden;
          will-change: transform;
          &.flap-card-semi-circle-left {
            border-radius: px2rem(24) 0 0 px2rem(24);
            background-position: center right;
            transform-origin: right;
          }
          &.flap-card-semi-circle-right {
            border-radius: 0 px2rem(24) px2rem(24) 0;
            background-position: center left;
            transform-origin: left;
          }
        }
      }
    }
    .point-wrapper {
      z-index: 1500;
      @include absCenter;
      .point {
        border-radius: 50%;
        @include absCenter;
        &.animation {
          @for $i from 1 to length($moves) {
            &:nth-child(#{$i}) {
              @include move($i);
            }
          }
        }
      }
    }
  }
  .book-card {
    position: relative;
    width: 65%;
    max-width: px2rem(400);
    box-sizing: border-box;
    border-radius: px2rem(15);
    background: #ffffff;
    &.animation {
      animation: scale 0.3s ease-in both;
      @keyframes scale {
        0% {
          transform: scale(0);
          opacity: 0;
        }
        100% {
          transform: scale(1);
          opacity: 1;
        }
      }
    }
    .book-card-wrapper {
      width: 100%;
      height: 100%;
      margin-bottom: px2rem(30);
      @include columnTop;
      .img-wrapper {
        width: 100%;
        margin-top: px2rem(20);
        @include center;
        .img {
          width: px2rem(90);
          height: px2rem(130);
        }
      }
      .content-wrapper {
        padding: 0 px2rem(20);
        margin-top: px2rem(20);
        .content-title {
          color: #333333;
          font-weight: bold;
          font-size: px2rem(18);
          line-height: px2rem(20);
          text-align: center;
          @include ellipsis2(2);
        }
        .content-author {
          margin-top: px2rem(10);
          text-align: center;
        }
        .content-category {
          color: #999;
          font-size: px2rem(14);
          margin-top: px2rem(10);
          text-align: center;
        }
      }
      .read-btn {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 1100;
        width: 100%;
        border-radius: 0 0 px2rem(15) px2rem(15);
        padding: px2rem(15) 0;
        text-align: center;
        color: white;
        font-size: px2rem(14);
        background: $color-blue;
      }
    }
  }
  .close-btn-wrapper {
    position: absolute;
    left: 0;
    bottom: px2rem(30);
    z-index: 1111;
    width: 100%;
    @include center;
    .icon-close {
      width: px2rem(45);
      height: px2rem(45);
      font-size: px2rem(25);
      border-radius: 50%;
      background: #333;
      color: #fff;
      @include center;
    }
  }
}
</style>
